const fs = require('fs');
const path = require('path');

const staticDir = path.join(__dirname, '../static');

// 存储图片的哈希值，用于检测重复
const imageHashes = new Map();

// 计算文件的MD5哈希值
function calculateFileHash(filePath) {
    const crypto = require('crypto');
    const fileBuffer = fs.readFileSync(filePath);
    const hashSum = crypto.createHash('md5');
    hashSum.update(fileBuffer);
    return hashSum.digest('hex');
}

// 递归处理目录
function processDirectory(dir) {
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    
    for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        
        if (entry.isDirectory()) {
            processDirectory(fullPath);
        } else if (entry.isFile() && /\.(jpg|jpeg|png|gif)$/i.test(entry.name)) {
            const hash = calculateFileHash(fullPath);
            
            if (imageHashes.has(hash)) {
                // 找到重复文件
                const originalPath = imageHashes.get(hash);
                console.log(`发现重复图片：`);
                console.log(`  原始文件：${path.relative(process.cwd(), originalPath)}`);
                console.log(`  重复文件：${path.relative(process.cwd(), fullPath)}`);
                
                // 删除重复文件
                fs.unlinkSync(fullPath);
                console.log(`  已删除重复文件：${path.relative(process.cwd(), fullPath)}`);
            } else {
                imageHashes.set(hash, fullPath);
            }
        }
    }
}

// 更新图片引用路径
function updateImageReferences() {
    // 获取所有Vue文件
    const vueFiles = [];
    function findVueFiles(dir) {
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        for (const entry of entries) {
            const fullPath = path.join(dir, entry.name);
            if (entry.isDirectory() && !fullPath.includes('node_modules')) {
                findVueFiles(fullPath);
            } else if (entry.isFile() && entry.name.endsWith('.vue')) {
                vueFiles.push(fullPath);
            }
        }
    }
    
    findVueFiles(path.join(__dirname, '..'));
    
    // 更新每个Vue文件中的图片引用
    vueFiles.forEach(file => {
        let content = fs.readFileSync(file, 'utf8');
        const originalContent = content;
        
        // 更新图片引用路径
        content = content.replace(
            /\/static\/([^"']+\.(?:jpg|jpeg|png|gif))/g,
            (match, imagePath) => {
                const fullImagePath = path.join(staticDir, imagePath);
                if (fs.existsSync(fullImagePath)) {
                    // 如果图片存在，保持原路径
                    return match;
                } else {
                    // 如果图片不存在，尝试在优化目录中查找
                    const optimizedPath = path.join(staticDir, 'optimized', imagePath);
                    if (fs.existsSync(optimizedPath)) {
                        return `/static/optimized/${imagePath}`;
                    }
                }
                return match;
            }
        );
        
        // 如果内容有变化，写入文件
        if (content !== originalContent) {
            fs.writeFileSync(file, content, 'utf8');
            console.log(`已更新文件：${path.relative(process.cwd(), file)}`);
        }
    });
}

// 开始处理
console.log('开始清理重复图片...');
processDirectory(staticDir);
console.log('\n开始更新图片引用路径...');
updateImageReferences();
console.log('\n处理完成！'); 